<template>
    <div class="editor">
        <Editor
            :defaultConfig="editorConfig"
            :mode="mode"
            v-model="valueHtml"
            style="height: 400px; overflow-y: hidden"
            @onCreated="handleCreated"
            @onChange="handleChange"
        />
    </div>
</template>

<script setup>
import "@wangeditor/editor/dist/css/style.css";
import {
    onBeforeUnmount,
    ref,
    shallowRef,
    onMounted,
    inject,
    reactive,
} from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import cfile from "../utils/UploadFiles.js";

// import { resolve } from 'path';
// import { storeToRefs } from "pinia";
const SparkMD5 = inject("SparkMD5");
const axios = inject("axios");
// const epStore = inject("epStore");
const server_url = inject("server_url");
// 编辑器实例，必须用 shallowRef，重要！
// shallowRef只有第一层key是响应式的
const editorRef = shallowRef();
const toolbarConfig = {
    excludeKeys: ["uploadVideo"],
}; // 默认配置
const editorConfig = { placeholder: "请输入内容..." }; // 默认内容
const mode = ref("default");
const valueHtml = ref("");

// console.log(server_url);

const props = defineProps({
    modelValue: {
        type: String,
        default: "",
    },
});

const emit = defineEmits(["update:model-value"]); // emit需要在后部声明要抛出的事件
let initFinished = false; // 只要值不在页面上渲染就不需要ref或reavtive


editorConfig.MENU_CONF = {};
editorConfig.MENU_CONF["uploadImage"] = {
    // 自定义上传
    async customUpload(file, insertFn) {
        // 这里可以拿到文件
        // console.log(file);
        cfile.selectFilesDirect(file); // 获取文件
        cfile.uploadFile(() => {
            getImg(insertFn);
            // cfile.File_Path = [];
            // cfile.user_files = [];
        });
    },
};

function getImg(insertFn) {
    // console.log(" cfile.File_Path",  cfile.File_Path);
    // console.log(server_url);
    let url = server_url + "/public/upload/" + cfile.File_Path[0];
    let alt = null;
    let href = null;
    // console.log("url", url);
    // file 即选中的文件
    // 自己实现上传，并得到图片 url alt href
    // 最后插入图片
    insertFn(url, alt, href);
}


// 从外部向内部传值
// 10毫秒后进行传值操作
onMounted(() => {
    setTimeout(() => {
        valueHtml.value = props.modelValue;
        initFinished = true;
    }, 10);
});

// 组件销毁时，也及时销毁编辑器，重要！
onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;

    editor.destroy();
});

// 编辑器回调函数
const handleCreated = (editor) => {
    // console.log('created', editor);
    editorRef.value = editor; // 记录 editor 实例，重要！
};

const handleChange = (editor) => {
    if (initFinished) {
        emit("update:model-value", valueHtml.value);
    }
};
</script>

<style lang="scss" scoped>
.editor {
    margin-top: 100px;
    top: 100px
}
</style>
